# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os

from django.contrib.contenttypes.models import ContentType
from django.db.models import FileField
from django.db.models.loading import get_model
from wenlincms.generic.models import Keyword, AssignedKeyword
from wenlincms.utils.urls import slugify

from mainsys.settings import PROJECT_ROOT
from wlapps.utils.base62 import wlencode

# 本文件用于存储post_save信号的相关操作，禁止在这些文件中使用save()，会引起死循环
current_path = os.path.join(PROJECT_ROOT, '../wlapps/utils')


# 同步关键词到M2M表供admin后台使用
def sync_keywords(string, pk, atype, ctype):
    # 获取关键词id
    keywords = string.split(' ')
    if len(keywords):
        # 获取模型id
        cmod = ContentType.objects.get(app_label=atype, model=ctype)
        content_id = cmod.id
        # 已存在的关键词
        existing_objs = AssignedKeyword.objects.filter(content_type=content_id, object_pk=pk)
        existing_list = [key.keyword.id for key in existing_objs]
        # 删除多余的关键词
        for e_obj in existing_objs:
            if e_obj.keyword.title not in keywords:
                existing_objs.filter(id=e_obj.id).delete()
        # 添加新关键词
        order = -1
        for ky in keywords:
            if len(ky):
                order += 1
                # 下面有魔法，请勿轻易改动，非池
                key1_objs = Keyword.objects.filter(title__exact=ky)
                key2_objs = Keyword.objects.filter(title__exact=str(ky.encode('utf8')))
                key_obj = key2_objs[0] if len(key2_objs) else None
                if key_obj is None and len(key1_objs):
                    key_obj = key1_objs[0]
                if key_obj is not None:
                    if key_obj.id not in existing_list:
                        new_data = {'content_type': cmod, 'object_pk': pk, 'keyword': key_obj, '_order': order}
                        AssignedKeyword.objects.create(**new_data)
                    else:
                        new_data = {'_order': order}
                        existing_objs.filter(keyword=key_obj.id).update(**new_data)
                # 新建关键词
                else:
                    new_data = {'title': ky}
                    new_obj = Keyword.objects.create(**new_data)
                    new_assign = {'content_type': cmod, 'object_pk': pk, 'keyword': new_obj, '_order': order}
                    AssignedKeyword.objects.create(**new_assign)


# 更新slug，根据id生成base62编码，防抓取并保证唯一性
def sync_slugs(pk, atype, ctype):
    # 动态获取模型
    cmod = get_model(atype, ctype)
    the_obj = cmod.objects.get(id=pk)
    new_slug = wlencode(int(pk), addcrc=True) + '-' + slugify(the_obj.title)
    new_data = {'slug': new_slug}
    cmod.objects.filter(id=pk).update(**new_data)


# 在mode被删除时同时删除media中的文件
# 和 pre_delete 信号结合使用
# 一般不启用这个函数，没必要每个文件都删除
def file_cleanup_on_delete(sender, **kwargs):
    inst = kwargs['instance']
    for fieldname in sender._meta.get_all_field_names():
        try:
            field = sender._meta.get_field(fieldname)
        except Exception:
            field = None
        if field and isinstance(field, FileField):
            f = getattr(inst, fieldname)
            if hasattr(f, 'path') and os.path.exists(f.path):
                os.remove(f.path)


# 在mode中file改变时同时删除media中的原来的文件
# 和 pre_save 信号结合使用
# 一般不启用这个函数，没必要每个文件都删除
def file_cleanup_on_change(sender, **kwargs):
    inst = kwargs['instance']
    if not inst.pk:
        return False

    for fieldname in sender._meta.get_all_field_names():
        try:
            field = sender._meta.get_field(fieldname)
        except Exception:
            field = None
        if field and isinstance(field, FileField):
            f = getattr(inst, fieldname)
            pre_f = sender.objects.get(pk=inst.pk).fieldname
            if hasattr(f, 'path') and hasattr(pre_f, 'path'):
                if f.path != pre_f.path and os.path.exists(pre_f.path):
                    os.remove(pre_f.path)
